<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="部门名称" prop="departmentname">
        <el-input
          v-model="queryParams.departmentname"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门经理的员工ID" prop="managerid">
        <el-input
          v-model="queryParams.managerid"
          placeholder="部门经理的员工ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:departments:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:departments:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:departments:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:departments:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="departmentsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="部门的唯一标识" align="center" prop="departmentid" />
      <el-table-column label="部门名称" align="center" prop="departmentname" />
      <el-table-column label="部门经理的员工ID，外键关联员工表" align="center" prop="managerid" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:departments:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:departments:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination      
        :total="total"
        v-model:currentPage="queryParams.pageNum"
        v-model:pageSize="queryParams.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    <!-- 添加或修改存储部门信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="departmentsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="部门名称" prop="departmentname">
          <el-input v-model="form.departmentname" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门经理的员工ID，外键关联员工表" prop="managerid">
          <el-input v-model="form.managerid" placeholder="请输入部门经理的员工ID，外键关联员工表" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Departments">
import { getCurrentInstance,ref,reactive,toRefs} from 'vue';
import { ElMessage ,ElMessageBox} from 'element-plus';
import { listDepartments, getDepartments, delDepartments, addDepartments, updateDepartments } from "@/api/system/departments";

const { proxy } = getCurrentInstance();

const departmentsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    DepartmentName: null,
    ManagerID: null
  },
  rules: {
    DepartmentName: [
      { required: true, message: "部门名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询存储部门信息列表 */
function getList() {
  loading.value = true;
  listDepartments(queryParams.value).then(response => {
    console.log("response",response)
    departmentsList.value = response.data.records;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
const departmentRef = ref(null);
// 表单重置
function reset() {
  form.value = {
    departmentid: null,
    departmentname: null,
    managerid: null
  };
  // proxy.resetForm("departmentsRef");
  if (departmentRef.value) { // 确保 usersRef 不是 null
    departmentRef.value.resetFields();
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  if (queryRef.value) {
    queryRef.value.resetFields();
  }
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  queryParams.name = null;
  queryParams.username = null;
  queryParams.phone = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.departmentid);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加存储部门信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _DepartmentID = row.departmentid || ids.value
  getDepartments(_DepartmentID).then(response => {
    console.log("response",response)
    form.value = response;
    open.value = true;
    title.value = "修改存储部门信息";
  });
}
// 分页
function handleSizeChange(newSize) {
  queryParams.pageSize = newSize;
  queryParams.pageNum = 1; // 重置页码为第一页
  getList();
}

function handleCurrentChange(newPage) {
  queryParams.pageNum = newPage;
  getList();
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["departmentsRef"].validate(valid => {
    if (valid) {
      if (form.value.departmentid != null) {
        updateDepartments(form.value).then(response => {
          ElMessage({
            message: '修改成功',
            type: 'success'
          }); 
          open.value = false;
          getList();
        });
      } else {
        addDepartments(form.value).then(response => {
          ElMessage({
            message: '新增成功',
            type: 'success'
          }); 
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row) {
  const _DepartmentIDs = row.departmentid || ids.value;

  try {
    // 等待用户确认
    await ElMessageBox.confirm(
      '是否确认删除存储系统用户信息编号为"' + _DepartmentIDs + '"的数据项？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    // 用户确认后，执行删除操作
    const response = await delDepartments(_DepartmentIDs);
    console.log("response1", response);

    // 根据响应结果处理提示信息
    if (response.code === 200) {
      getList();
      ElMessage({
        message: "删除成功",
        type: "success"
      });
    } else if (response.code === 400) {
      ElMessage({
        message: "该部门还存在有员工",
        type: "warning"
      });
    }
  } catch (error) {
    // 用户取消操作或发生其他错误
    ElMessage({
      message: "删除操作已取消",
      type: "info"
    });
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/departments/export', {
    ...queryParams.value
  }, `departments_${new Date().getTime()}.xlsx`)
}

getList();
</script>
